<template>
	<view class="main">
		<u-modal v-model="show" @confirm="confirm" :content="content" cancel-text="否" confirm-text='是'
			show-cancel-button='true'></u-modal>
		<u-toast ref="uToast" />
		<view class="">
			<view class="title">
				<alltitleVue :title="title" :url="url" />
			</view>
			<view class="hos-img">
				<image :src="titleImg" mode=""></image>
			</view>
			<view class="hos-name">
				成都西南中医医院患者端
			</view>
			<view class="btn">
				<view class="btn-box">
					<view class="" :class="{'zindex':!checked}" @click="dian">
						一键快捷登录
					</view>
					<button open-type="getPhoneNumber" :disabled="!checked" class="login_button"
						@getphonenumber="login">一键快捷登录</button>
				</view>

			</view>
			<view class="xieyi">

				<view class="selectAgreement">
					<view class="checked" @click="onChecked" :class="{ checkedbg: checked }">
						<u-icon v-show="checked" color="#fff" size="32" name="checkbox-mark"></u-icon>

					</view>
					<view class="text">
						<text>{{ text }}</text>
						<text class="link" @click="jumpAgreement('patient_service')">
							{{ linkText1 }}
						</text>
						<text>和</text>
						<text class="link" @click="jumpAgreement('patient_privacy')">
							{{ linkText2 }}{{soul?'.':''}}
						</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		toast,
		getStore,
		setStore,
		removeStore
	} from "@/utils/index";
	import title from '../../components/title.vue';
	import {
		listByIds,
		logout,
		getPhone,
		wxlogin,

	} from '../../service/api.js';
	import config from "../../utils/config";
	export default {

		data() {
			return {
				url: config.host,
				titleImg: config.ossHost + "2024/12/23/f0ed89db09b448a7bbb3a9d88be573b9.png",
				show: false,
				checked: false,
				text: "登录/注册代表你已同意",
				soul: String,
				linkText1: "《服务协议》",
				linkText2: '《隐私协议》',
				content: "是否已同意并阅读《服务协议》和《隐私协议》",
				wxparams: {
					deviceType: "",
					xcxCode: '',
					clientKey: "xcx",
					grantType: "xcx",
					clientId: "af80f6d0dc2d2f09587d2bd25e384d84",
					mobile: ""
				},
			}
		},
		computed: {
			service() {
				return getStore("service") || false
			},
			privace() {
				return getStore("privace") || false
			}
		},
		onShow() {

			if (this.service && this.privace) {
				this.checked = true;
			}
		},
		methods: {



			onChecked() {
				this.checked = !this.checked;
			},

			jumpAgreement(e) {
				uni.navigateTo({
					url: `/My/policy?type=${e}`
				})
			},
			dian() {
				if (!this.checked) {
					this.show = true;
					return
				}
			},
			confirm() {
				this.checked = true;

			},
			async getInfo(accessToken) {
				try {
					const response = await uni.request({
						url: this.url + 'app/member/getInfo', // 注意这里的拼接，如果 this.url 为 undefined 会出错
						method: 'GET',
						header: {
							'Authorization': `Bearer ${accessToken}`, // 将 token 添加到请求头
							'content-type': 'application/json',
						},
					});

					if (response && response.data) {
						console.log('请求成功:', response.data);
						return response.data;
					} else {
						console.log('没有获取到数据');
					}
				} catch (error) {
					console.error('请求失败:', error);
				}
			},



			async login(e) {
				var detail = e.detail;

				if (detail.errMsg == "getPhoneNumber:ok") {
					const code = detail.code;
					try {
						// 使用 await 直接获取响应结果
						const response = await uni.request({
							url: this.url + 'wxAuth/getPhoneNumber',
							method: 'POST',
							header: {
								'content-type': 'application/json'
							},
							data: {
								code: code,
								tenantId: '934485'
							},
						});
						// 检查是否包含手机号
						if (response && response.data && response.data.phone_info && response.data.phone_info
							.phoneNumber) {
							const userId = response.data.phone_info.phoneNumber;
							this.wxparams.mobile = userId;
							// 获取设备信息
							const systemInfo = await uni.getSystemInfo();
							console.log(systemInfo);
							const model = systemInfo.model;
							const system = systemInfo.system;
							// 微信登录
							const loginRes = await new Promise((resolve, reject) => {
								uni.login({
									success: (res) => resolve(res),
									fail: (err) => reject(err),
								});
							});
							if (loginRes.code) {
								// 保存微信登录的 code
								const wxCode = loginRes.code;
								this.wxparams.xcxCode = wxCode;

								// 调用 wxlogin 登录函数
								const loginResult = await wxlogin(JSON.stringify(this.wxparams));

								// 登录成功后的处理
								if (loginResult && loginResult.code == 200) {
									// 存储用户信息
									setStore("token", loginResult.data.access_token); // 存储用户 access_token
									setStore("openid", loginResult.data.openid); // 存储用户 openid

									// 获取用户信息
									const info = await this.getInfo(loginResult.data.access_token);

									if (info.code == 200) {
										// 存储用户详细信息
										setStore("info", JSON.stringify(info.data.member));

										// 只有在存储成功后才跳转
										uni.navigateBack({
											delta: 1,
										});
										// 显示登录成功的提示
										uni.showToast({
											title: '登录成功',
											icon: 'success', // 使用成功图标
											duration: 2000 // 2秒后自动消失
										});
									} else {
										uni.showModal({
											title: "错误",
											content: "获取用户信息失败",
										});
									}

									// 显示登录成功的提示
									this.$refs.uToast.show({
										title: '登录成功',
										type: 'success',
									});
								} else {
									uni.showModal({
										title: "错误",
										content: loginResult.msg,
									});
								}
							} else {
								console.log('微信登录失败', loginRes.errMsg);
								uni.showModal({
									title: "错误",
									content: "微信登录失败，请重试",
								});
							}
						} else {
							uni.showModal({
								title: "错误",
								content: "获取手机号失败，请重试",
							});
						}
					} catch (err) {
						// 捕获异常处理
						console.error(err);
						uni.showModal({
							title: "网络错误",
							content: "无法连接服务器，请检查网络",
						});
					}
				} else {
					uni.showModal({
						title: "授权失败",
						content: "用户未授权手机号",
					});
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.main {
		width: 100%;
		height: 100vh;
		background: #fff;
	}

	.u-iconfont {
		top: 4rpx;
	}

	.hos-img {
		width: 196rpx;
		height: 196rpx;

		margin: auto;
		margin-top: 156rpx;

		image {
			width: 196rpx;
			height: 196rpx;
			margin: auto;
		}
	}

	.hos-name {

		width: 352rpx;
		text-align: center;
		height: 42rpx;
		font-family: MiSans, MiSans;
		font-weight: bold;
		font-size: 32rpx;
		color: #673A34;
		line-height: 38rpx;
		margin: auto;
		margin-top: 24rpx;

	}

	.btn {

		margin: auto;
		margin-top: 160rpx;
		font-size: 32rpx;
		text-align: center;
		line-height: 74rpx;
		width: 654rpx;
		height: 74rpx;
		color: #FFFFFF;
		background: #CCA566;
		border-radius: 8rpx 8rpx 8rpx 8rpx;

		.btn-box {
			position: relative;

			view {
				color: #fff;
			}

			.zindex {
				width: 100%;
				color: #FFFFFF;
				position: absolute;
				top: 0;
				left: 0;
				z-index: 10;
			}

			button {
				width: 100%;
				opacity: 0;
				position: absolute;
				top: 0;
				left: 0;
			}
		}
	}

	.xieyi {
		width: 100%;
		left: 50%;
		margin-left: -50%;
		position: fixed;
		bottom: 50rpx;
		display: flex;
		justify-content: center;
		text-align: center;
		font-size: 24rpx;
		color: #808080;

		text {
			color: #1A1A1A;
		}
	}

	.selectAgreement {

		display: flex;
		align-items: center;

		.checked {
			width: 40rpx;
			height: 40rpx;
			border: 1px solid #c8c7cc;
			background-color: #fff;
			border-radius: 3px;
			box-sizing: border-box;
			display: flex;
			align-items: center;
			margin-right: 10rpx;
			border-radius: 50%;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.checkedbg {
			background-color: #CCA566;
			border: 1px solid #fff;
		}

		.text {
			display: flex;
			align-items: center;

			text {
				font-size: 12px;
				color: #555555;
				margin-left: 10rpx;
			}

			.link {
				color: #CCA566;
			}
		}
	}
</style>